package 数据结构.章节09._162_带最小值的栈;

import 数据结构.章节09._148_双链表.ListNode;
import 数据结构.章节09._160_栈.MyStack;

import java.util.EmptyStackException;

/**
 * @author 挚爱之夕
 * @date 2021/10/13 - 10 - 13 - 17:05
 * @Description: 数据结构.章节09._162_带最小值的栈
 * @Version: 1.0
 */
public class StackWithMin extends MyStack<Integer> {

    @Override
    public void push(Integer e) {
        super.add(e);
        if(brother.isEmpty()){
            brother.add(e);
        }else{
            if(e<min()){
                brother.add(e);
            }else{
                brother.add(min());
            }
        }
    }

    @Override
    public Integer pop() {
        if(size<=0) throw new EmptyStackException();
        //得到元素
        ListNode<Integer> now = last.getPre();
        Integer res = now.getData();
        //删除操作
        now.getPre().setNext(last);
        last.setPre(now.getPre());
        now.setPre(null);
        now.setNext(null);
        size--;
        brother.pop();
        return res;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public Integer peek() {
        return last.getPre().getData();
    }

    @Override
    public int getSize() {
        return size;
    }
    //辅助栈
    MyStack<Integer> brother = new MyStack<>();
    public int min(){
        if(brother.isEmpty())
            throw new EmptyStackException();
        else
            return brother.peek();
    }
}
